package com.example.demo08;

import android.os.Bundle;
import android.os.FileObserver;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SDObservePage extends Fragment {
	TextView text;
	SdObv obv;
	StringBuilder sb = new StringBuilder();
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		obv = new SdObv("/sdcard/");
		obv.startWatching();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		obv.stopWatching();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_text, container, false);
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		
		text = (TextView) view.findViewById(R.id.text);
		sb.append(SystemClock.uptimeMillis()).append(":SD卡监听中...").append('\n');
		
		text.setText(sb.toString());
	}
	
	final Runnable r = new Runnable() {
		
		@Override
		public void run() {
			text.setText(sb.toString());
		}
	};
	
	void update() {
		getActivity().runOnUiThread(r);
	}
	
	class SdObv extends FileObserver {

		public SdObv(String path) {
			super(path);
		}

		@Override
		public void onEvent(int event, String path) {
			switch (event) {
			case CREATE:
				sb.append("文件创建：").append(path).append('\n');
				break;
			case DELETE:
				sb.append("文件删除：").append(path).append('\n');
				break;
			default:
				sb.append("event:" + event + ", path=" + path).append('\n');
				break;
			}
			
			update();
		}
	}
}
